package com.wiloon.androidx;

import android.app.Application;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.wiloon.androidx.asynctask.AsyncTaskActivity;
import com.wiloon.androidx.asynctask.ThreadHandlerActivity;
import com.wiloon.androidx.broadcast.BroadcastReceiverActivity;
import com.wiloon.androidx.fragment.FragmentActivity;
import com.wiloon.androidx.list.ExpandableListViewActivity;
import com.wiloon.androidx.list.ListViewActivity;
import com.wiloon.androidx.network.TrafficService;
import com.wiloon.androidx.network.Traffic_Service;
import com.wiloon.androidx.service.LocalService;
import com.wiloon.androidx.utils.JsonHelper;

import org.apache.log4j.Logger;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private static final Logger logger = Logger.getLogger(MainActivity.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logger.debug("logger on created.");
        jsonTest();
        setContentView(R.layout.activity_main);
        TextView editText = (TextView) findViewById(R.id.textHelloWorld);
        editText.setText("Text view;" + getCurrentDate());
        setListener();

        //error under ART environment, since Gson cannot handle the shadow object


        //imei
        String imei = ((TelephonyManager) this.getSystemService(TELEPHONY_SERVICE)).getDeviceId();

        logger.debug("IMEI=" + imei);
        logger.debug("getDeviceSoftwareVersion=" + ((TelephonyManager) this.getSystemService(TELEPHONY_SERVICE)).getDeviceSoftwareVersion());

        try {
            Application APP = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication", new Class[0]).invoke(null, (Object[]) null);
            logger.debug("dex dir=" + APP.getDir("dex", 0).getAbsolutePath());
            logger.debug("getApplicationInfo=" + APP.getApplicationInfo().nativeLibraryDir);

            File jarPath = new File(APP.getDir("dex", 0), "sfnt_protected.jar");
            logger.debug("jar path=" + jarPath.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        addCornerIcon();

    }

    private void addCornerIcon() {
        boolean badgeCountRegistered = false;
        Uri uri = Uri.parse("content://com.sec.badge/apps");

        Cursor c = getContentResolver().query(uri, null, null, null, null);
        if (c == null) {
            return;
        }

        try {
            if (!c.moveToFirst()) {
                return;
            }

            c.moveToPosition(-1);
            while (c.moveToNext()) {
                String pkg = c.getString(1);
                String clazz = c.getString(2);
                int badgeCount = c.getInt(3);
                logger.debug("package: " + pkg + ", class: " + clazz + ", count: " + String.valueOf(badgeCount));
                if (clazz.equals("com.wiloon.androidx")) {
                    badgeCountRegistered = true;
                }
            }
        } finally {
            c.close();
        }

        if (!badgeCountRegistered) {
            ContentValues cv = new ContentValues();
            cv.put("package", getPackageName());
// Name of your activity declared in the manifest as android.intent.action.MAIN.
// Must be fully qualified name as shown below
            cv.put("class", "com.wiloon.androidx");
            cv.put("badgecount", 1); // integer count you want to display

// Execute insert
            getContentResolver().insert(Uri.parse("content://com.sec.badge/apps"), cv);
        } else {
            ContentValues cv = new ContentValues();
            cv.put("badgecount", 2);
            getContentResolver().update(Uri.parse("content://com.sec.badge/apps"), cv, "package=?", new String[]{getPackageName()});
        }
    }

    private void jsonTest() {
        logger.debug("json test");
        JsonHelper jh = new JsonHelper();
//        Map map = new HashMap<Integer, MyValue>();
//        map.put(1, new MyValue().name = "abc");
//        map.put(2, new MyValue().name = "def");


        Map map = new HashMap();
        map.put("funName", "GetAndroidVersion");
        map.put("serialVersionUID", -4308869841788373801l);
        map.put("language", "zh");
        map.put("APPVersion", "1.1.1");
        map.put("funName", "GetAndroidVersion");
        map.put("funName", "GetAndroidVersion");
        map.put("funName", "GetAndroidVersion");
        map.put("funName", "GetAndroidVersion");

        jh.jacksonTest(map);
        jh.fastJsonTest(map);
        jh.gsonTest(map);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        logger.debug("onCreateOptionsMenu");
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void startCustomService() {
        logger.debug("startCustomService");
        // startService(new
        // Intent("com.wiloon.androidlab.service.LocalService"));

        // Intent intent = new
        // Intent(this,com.wiloon.androidlab.service.LocalService.class);
        Intent intent = new Intent(this, LocalService.class);
        startService(intent);

    }

    private void startTrafficService() {
        logger.debug("startTrafficService");
        // startService(new
        // Intent("com.wiloon.androidlab.service.LocalService"));

        // Intent intent = new
        // Intent(this,com.wiloon.androidlab.service.LocalService.class);
        Intent intent = new Intent(this, TrafficService.class);
        startService(intent);
    }

    private String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy/MM/dd HH:mm:ss", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }

    public void buttonFirstOnClick(View view) {
        logger.debug("button clicked.");
        startCustomService();
    }

    @Override
    public void onStart() {
        logger.debug("onStart");
        super.onStart();
    }

    @Override
    public void onResume() {
        logger.debug("onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        logger.debug("onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        logger.debug("onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        logger.debug("onDestroy");
        super.onDestroy();
    }

    private void setListener() {
        Button buttonFoo = (Button) findViewById(R.id.button_foo);
        buttonFoo.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                logger.debug("btn to foo clicked.");
                Intent intent = new Intent();
                intent.putExtra("name", "foo");
                intent.setClass(MainActivity.this, FooActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button buttonContentProvider = (Button) findViewById(R.id.button_content_provider);
        buttonContentProvider.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                logger.debug("btn to cp clicked.");

                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this,
                        ContentProviderActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }

        });

        Button buttonCanvas = (Button) findViewById(R.id.button_canvas);
        buttonCanvas.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, CanvasDemoActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        //to fragment
        Button buttonToFragment = (Button) findViewById(R.id.button_fragment);
        buttonToFragment.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, FragmentActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        //to list view
        Button btnToListView = (Button) findViewById(R.id.btnToListActivity);
        btnToListView.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, ListViewActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        //expandable list view

        Button btnToExpandableListView = (Button) findViewById(R.id.btnExpandableListView);
        btnToExpandableListView.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, ExpandableListViewActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnToProgressBarActivity = (Button) findViewById(R.id.btnProgressBarActivity);
        btnToProgressBarActivity.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, ProgressBarActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnCameraActivity = (Button) findViewById(R.id.btnCameraActivity);
        btnCameraActivity.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, MyCameraActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnThreadHandler = (Button) findViewById(R.id.btnThreadHandler);
        btnThreadHandler.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, ThreadHandlerActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnAsyncTaskActivity = (Button) findViewById(R.id.btnAsyncTaskActivity);
        btnAsyncTaskActivity.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, AsyncTaskActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnBroadcastActivity = (Button) findViewById(R.id.btnBroadcastActivity);
        btnBroadcastActivity.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("name", "cp");
                intent.setClass(MainActivity.this, BroadcastReceiverActivity.class);
                MainActivity.this.startActivity(intent);
                MainActivity.this.finish();
            }
        });

        Button btnStartSevice = (Button) findViewById(R.id.btnStartService);
        btnStartSevice.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                logger.debug("on start service clicked.");
                startTrafficService();
            }
        });


    }
}
